package com.quectel.core.module.partybuilding.service.impl;


import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dao.PartyBuildingHelpRecordDao;
import com.quectel.core.module.partybuilding.dto.*;
import com.quectel.core.module.partybuilding.entity.PartyBuildingHelpRecordEntity;
import com.quectel.core.module.partybuilding.service.PartyBuildingHelpRecordPersonBindingService;
import com.quectel.core.module.partybuilding.service.PartyBuildingHelpRecordService;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:38
 */
@DubboService
public class PartyBuildingHelpRecordServiceImpl implements PartyBuildingHelpRecordService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyBuildingHelpRecordServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_BUILDING_HELP_RECORD_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_BUILDING_HELP_RECORD_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyBuildingHelpRecordDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_BUILDING_HELP_RECORD_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyPersonService partyPersonService;
    @Autowired
    private PartyBuildingHelpRecordDao partyBuildingHelpRecordDao;
    @Autowired
    private PartyBuildingHelpRecordPersonBindingService partyBuildingHelpRecordPersonBindingService;


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Long saveOrUpdate(PartyBuildingHelpRecordDto partyBuildingHelpRecordDto) {
        if (partyBuildingHelpRecordDto.getId() == null) {
            Long id = save(partyBuildingHelpRecordDto);
            partyBuildingHelpRecordDto.setId(id);
        } else {
            updateById(partyBuildingHelpRecordDto);
        }

        // 删除绑定关系
        partyBuildingHelpRecordPersonBindingService.deleteByRecordId(partyBuildingHelpRecordDto.getId());

        // 绑定下党员信息到中间表
        for (PartyBuildingHelpRecordPersonBindingDto bindingDto : partyBuildingHelpRecordDto.getBindPerson()) {
            bindingDto.setRecordId(partyBuildingHelpRecordDto.getId());
            partyBuildingHelpRecordPersonBindingService.save(bindingDto);
        }
        return partyBuildingHelpRecordDto.getId();
    }


    @Override
    public PartyBuildingHelpRecordDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_BUILDING_HELP_RECORD_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyBuildingHelpRecordDto selectById(Long id){
            PartyBuildingHelpRecordEntity entity = partyBuildingHelpRecordDao.selectById(id);

        PartyBuildingHelpRecordDto partyBuildingHelpRecordDto = paddingField(CopyUtils.copyObj(entity, PartyBuildingHelpRecordDto.class));

        if(CollectionUtils.isNotEmpty(partyBuildingHelpRecordDto.getBindPerson())){
            List<PartyPersonResp> list = new ArrayList<>(partyBuildingHelpRecordDto.getBindPerson().size());
            for (PartyBuildingHelpRecordPersonBindingDto bindingDto : partyBuildingHelpRecordDto.getBindPerson()) {
                PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(bindingDto.getPersonId());
                PartyPersonResp result = new PartyPersonResp();
                result.setId(partyPersonDto.getId());
                result.setTenantId(partyPersonDto.getTenantId());
                result.setPartyId(partyPersonDto.getPartyId());
                result.setName(partyPersonDto.getName());
                result.setMobile(partyPersonDto.getMobile());
                list.add(result);
            }
            partyBuildingHelpRecordDto.setPersonList(list);
        }

        return partyBuildingHelpRecordDto;
    }

    @Override
    public List<PartyBuildingHelpRecordDto> queryList(Map<String,Object> params){
        List<PartyBuildingHelpRecordEntity> list = partyBuildingHelpRecordDao.queryList(params);
        List<PartyBuildingHelpRecordDto> result =  CopyUtils.copyList(list,PartyBuildingHelpRecordDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyBuildingHelpRecordDto paddingField(PartyBuildingHelpRecordDto dto){
        if (dto != null){

            List<PartyBuildingHelpRecordPersonBindingDto> bindingDtos = partyBuildingHelpRecordPersonBindingService.selectByRecordId(dto.getId());
            dto.setBindPerson(bindingDtos);


            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
            if(partyOrganizationDto!=null){
                dto.setPartyName(partyOrganizationDto.getName());
            }


        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyBuildingHelpRecordDao.queryTotal(params);
    }

    @Override
    public Long save(PartyBuildingHelpRecordDto dto){
        PartyBuildingHelpRecordEntity entity = CopyUtils.copyObj(dto,PartyBuildingHelpRecordEntity.class);
        entity.setId(Snowflake.nextId());
        partyBuildingHelpRecordDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyBuildingHelpRecordDto dto){
        PartyBuildingHelpRecordEntity entity = CopyUtils.copyObj(dto,PartyBuildingHelpRecordEntity.class);

        partyBuildingHelpRecordDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyBuildingHelpRecordDto dto) {
       PartyBuildingHelpRecordEntity entity = CopyUtils.copyObj(dto,PartyBuildingHelpRecordEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyBuildingHelpRecordDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyBuildingHelpRecordDao.deleteById(id);

        partyBuildingHelpRecordPersonBindingService.deleteByRecordId(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
